import os
from typing import Dict, Any, Optional
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

class Config:
    """全局配置类"""
    
    # 基础配置
    APP_NAME = "AI视频翻译平台"
    APP_VERSION = "1.0.0"
    DEBUG = os.getenv("DEBUG", "False").lower() == "true"
    
    # 数据库配置
    DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./video_translation.db")
    
    # 文件存储配置
    UPLOAD_DIR = os.getenv("UPLOAD_DIR", "uploads")
    AUDIO_DIR = os.getenv("AUDIO_DIR", "audio")
    MAX_FILE_SIZE = int(os.getenv("MAX_FILE_SIZE", "100")) * 1024 * 1024  # 默认100MB
    
    # ASR服务配置
    ASR_CONFIG = {
        # 主要ASR服务选择 (google, whisper, azure, baidu, aliyun)
        "primary_service": os.getenv("ASR_PRIMARY_SERVICE", "google"),
        
        # 备用ASR服务 (当主要服务失败时使用)
        "fallback_service": os.getenv("ASR_FALLBACK_SERVICE", "whisper"),
        
        # 是否启用说话人识别
        "enable_speaker_diarization": os.getenv("ENABLE_SPEAKER_DIARIZATION", "False").lower() == "true",
        
        # 默认语言
        "default_language": os.getenv("ASR_DEFAULT_LANGUAGE", "zh-CN"),
        
        # 音频预处理配置
        "audio_preprocessing": {
            "sample_rate": int(os.getenv("AUDIO_SAMPLE_RATE", "16000")),
            "channels": int(os.getenv("AUDIO_CHANNELS", "1")),
            "format": os.getenv("AUDIO_FORMAT", "wav")
        }
    }
    
    # 各ASR服务的详细配置
    ASR_SERVICES = {
        # Google Speech Recognition (免费)
        "google": {
            "enabled": True,
            "name": "Google Speech Recognition",
            "description": "免费的语音识别服务，支持多种语言",
            "cost": "免费",
            "accuracy": "高",
            "rate_limit": "每分钟60次请求",
            "max_audio_length": 60,  # 秒
            "supported_languages": ["zh-CN", "en-US", "ja-JP", "ko-KR", "fr-FR", "de-DE", "es-ES", "ru-RU"],
            "config": {
                "use_ambient_noise_reduction": True,
                "ambient_duration": 0.5
            }
        },
        
        # OpenAI Whisper API (付费)
        "whisper": {
            "enabled": bool(os.getenv("OPENAI_API_KEY")),
            "name": "OpenAI Whisper API",
            "description": "高质量的语音识别服务，支持99种语言",
            "cost": "$0.006/分钟",
            "accuracy": "很高",
            "rate_limit": "每分钟50次请求",
            "max_audio_length": 300,  # 秒
            "supported_languages": ["auto", "zh", "en", "ja", "ko", "fr", "de", "es", "ru"],
            "config": {
                "api_key": os.getenv("OPENAI_API_KEY"),
                "api_url": "https://api.openai.com/v1/audio/transcriptions",
                "model": "whisper-1",
                "response_format": "verbose_json",
                "timestamp_granularities": ["word", "segment"]
            }
        },
        
        # Azure Speech Services (付费)
        "azure": {
            "enabled": bool(os.getenv("AZURE_SPEECH_KEY")),
            "name": "Azure Speech Services",
            "description": "微软的语音识别服务，支持实时转录",
            "cost": "$0.024/小时",
            "accuracy": "高",
            "rate_limit": "无限制",
            "max_audio_length": 0,  # 无限制
            "supported_languages": ["zh-CN", "en-US", "ja-JP", "ko-KR", "fr-FR", "de-DE", "es-ES", "ru-RU"],
            "config": {
                "subscription_key": os.getenv("AZURE_SPEECH_KEY"),
                "region": os.getenv("AZURE_SPEECH_REGION", "eastus"),
                "endpoint": os.getenv("AZURE_SPEECH_ENDPOINT")
            }
        },
        
        # 百度语音识别 (付费)
        "baidu": {
            "enabled": bool(os.getenv("BAIDU_APP_ID")),
            "name": "百度语音识别",
            "description": "百度AI平台的语音识别服务",
            "cost": "免费额度后付费",
            "accuracy": "高",
            "rate_limit": "QPS限制",
            "max_audio_length": 60,  # 秒
            "supported_languages": ["zh-CN", "en-US"],
            "config": {
                "app_id": os.getenv("BAIDU_APP_ID"),
                "api_key": os.getenv("BAIDU_API_KEY"),
                "secret_key": os.getenv("BAIDU_SECRET_KEY")
            }
        },
        
        # 阿里云智能语音 (付费)
        "aliyun": {
            "enabled": bool(os.getenv("ALIYUN_ACCESS_KEY_ID")),
            "name": "阿里云智能语音",
            "description": "阿里云的语音识别服务",
            "cost": "按量付费",
            "accuracy": "高",
            "rate_limit": "QPS限制",
            "max_audio_length": 60,  # 秒
            "supported_languages": ["zh-CN", "en-US"],
            "config": {
                "access_key_id": os.getenv("ALIYUN_ACCESS_KEY_ID"),
                "access_key_secret": os.getenv("ALIYUN_ACCESS_KEY_SECRET"),
                "region": os.getenv("ALIYUN_REGION", "cn-shanghai")
            }
        }
    }
    
    # 语言映射配置
    LANGUAGE_MAPPING = {
        "zh": "zh-CN",
        "zh-CN": "zh-CN",
        "zh-TW": "zh-TW",
        "en": "en-US",
        "en-US": "en-US",
        "en-GB": "en-GB",
        "ja": "ja-JP",
        "ja-JP": "ja-JP",
        "ko": "ko-KR",
        "ko-KR": "ko-KR",
        "fr": "fr-FR",
        "fr-FR": "fr-FR",
        "de": "de-DE",
        "de-DE": "de-DE",
        "es": "es-ES",
        "es-ES": "es-ES",
        "ru": "ru-RU",
        "ru-RU": "ru-RU"
    }
    
    # 语言显示名称
    LANGUAGE_NAMES = {
        "zh-CN": "简体中文",
        "zh-TW": "繁體中文",
        "en-US": "English (US)",
        "en-GB": "English (UK)",
        "ja-JP": "日本語",
        "ko-KR": "한국어",
        "fr-FR": "Français",
        "de-DE": "Deutsch",
        "es-ES": "Español",
        "ru-RU": "Русский"
    }
    
    # 说话人识别配置
    SPEAKER_DIARIZATION = {
        "enabled": ASR_CONFIG["enable_speaker_diarization"],
        "service": "pyannote",  # 暂时禁用
        "config": {
            "pyannote_token": os.getenv("PYANNOTE_TOKEN"),
            "min_speakers": 1,
            "max_speakers": 10
        }
    }
    
    # 日志配置
    LOGGING = {
        "level": os.getenv("LOG_LEVEL", "INFO"),
        "format": "%(asctime)s | %(levelname)-8s | %(name)s:%(funcName)s:%(lineno)d - %(message)s",
        "file": os.getenv("LOG_FILE", "app.log")
    }
    
    @classmethod
    def get_asr_service_config(cls, service_name: str) -> Optional[Dict[str, Any]]:
        """获取指定ASR服务的配置"""
        return cls.ASR_SERVICES.get(service_name)
    
    @classmethod
    def get_enabled_asr_services(cls) -> Dict[str, Dict[str, Any]]:
        """获取所有启用的ASR服务"""
        return {name: config for name, config in cls.ASR_SERVICES.items() 
                if config.get("enabled", False)}
    
    @classmethod
    def get_primary_asr_service(cls) -> str:
        """获取主要ASR服务名称"""
        primary = cls.ASR_CONFIG["primary_service"]
        if primary in cls.ASR_SERVICES and cls.ASR_SERVICES[primary]["enabled"]:
            return primary
        # 如果主要服务不可用，返回第一个可用的服务
        enabled_services = cls.get_enabled_asr_services()
        if enabled_services:
            return list(enabled_services.keys())[0]
        return "google"  # 默认返回google
    
    @classmethod
    def get_fallback_asr_service(cls) -> str:
        """获取备用ASR服务名称"""
        fallback = cls.ASR_CONFIG["fallback_service"]
        if fallback in cls.ASR_SERVICES and cls.ASR_SERVICES[fallback]["enabled"]:
            return fallback
        return cls.get_primary_asr_service()
    
    @classmethod
    def is_service_enabled(cls, service_name: str) -> bool:
        """检查指定服务是否启用"""
        service_config = cls.ASR_SERVICES.get(service_name)
        return service_config is not None and service_config.get("enabled", False)
    
    @classmethod
    def get_supported_languages(cls, service_name: str) -> list:
        """获取指定服务支持的语言列表"""
        service_config = cls.get_asr_service_config(service_name)
        if service_config:
            return service_config.get("supported_languages", [])
        return []
    
    @classmethod
    def get_language_name(cls, language_code: str) -> str:
        """获取语言代码对应的显示名称"""
        return cls.LANGUAGE_NAMES.get(language_code, language_code)
    
    @classmethod
    def get_mapped_language(cls, language_code: str) -> str:
        """获取映射后的语言代码"""
        return cls.LANGUAGE_MAPPING.get(language_code, language_code)

# 创建全局配置实例
config = Config() 